/*
 * SalesmanUI.java
 *
 * Created on May 31, 2007, 10:20 PM
 */

package gui;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author  Alirio
 */
public class SalesmanUI extends javax.swing.JFrame {
  
  private final String SQL_SELECT_1 = "select * from salesmen where salesman_id=?";
  private final String SQL_INSERT_1 = "insert into salesmen (salesman_id,name,region,top_serial,bottom_serial,comments,last_serial) " +
        "values(?,?,?,?,?,?,?)";
  private final String SQL_UPDATE_1 = "update salesmen set name=?, region=?, top_serial=?, bottom_serial=?, comments=?, last_serial=? " +
        "where salesman_id=?";
  private final String SQL_DELETE_1 = "delete from salesmen where salesman_id=?";
  
  private String mode="add";
  private Connection cnn;
  
  
  /** Creates new form SalesmanUI */
  public SalesmanUI() {
    initComponents();
  }
  
  private String validateFields() {
    if (textFieldDesde.getText().equals("")) {
      return "Campo Serial Desde en blanco!";
    }
    if (textFieldHasta.getText().equals("")) {
      return "Campo Serial Hasta en blanco!";
    }
    if (textFieldID.getText().equals("")) {
      return "Campo ID en blanco!";
    }
    if (textFieldLast.getText().equals("")) {
      return "Campo Ultimo Serial en blanco!";
    }
    if (textFieldName.getText().equals("")) {
      return "Campo Nombre en blanco!";
    }
    if (textFieldPwd.getText().equals("")) {
      return "Campo Password en blanco!";
    }
    if (textFieldRegion.getText().equals("")) {
      return "Campo Region en blanco!";
    }
    
    if (textFieldID.getText().length() > 3) {
      return "Campo ID no puede exceder de 3 caracteres!";
    }
    
    if (textFieldName.getText().length() > 35) {
      return "Campo Nombre no puede exceder de 35 caracteres!";
    }
    
    if (textFieldPwd.getText().length() > 10) {
      return "Campo Password no puede exceder de 10 caracteres!";
    }
    
    if (textFieldRegion.getText().length() > 3) {
      return "Campo Region no puede exceder de 3 caracteres!";
    }
    return "";
  }
  
  private void clearFields(boolean clearId) {
    if (clearId) {
      textFieldID.setText("");
    }
    textFieldName.setText("");
    textFieldRegion.setText("");
    textFieldDesde.setText("");
    textFieldHasta.setText("");
    textFieldPwd.setText("");
    textFieldLast.setText("");
  }
  
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
  private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    textFieldID = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    textFieldName = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    textFieldRegion = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    textFieldDesde = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    textFieldHasta = new javax.swing.JTextField();
    jLabel6 = new javax.swing.JLabel();
    textFieldPwd = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    textFieldLast = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Mantenimiento de Vendedores");
    jLabel1.setText("ID:");

    textFieldID.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        textFieldIDFocusLost(evt);
      }
    });

    jLabel2.setText("Nombre:");

    jLabel3.setText("Region:");

    jLabel4.setText("Serial (desde):");

    jLabel5.setText("Serial (hasta):");

    jLabel6.setText("Password:");

    jLabel7.setText("Ultimo Serial:");

    jButton1.setText("Nuevo");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });

    jButton2.setText("Grabar");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
      }
    });

    jButton3.setText("Eliminar");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton3ActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jLabel2)
              .addComponent(jLabel3)
              .addComponent(jLabel4)
              .addComponent(jLabel5)
              .addComponent(jLabel6)
              .addComponent(jLabel7))
            .addGap(46, 46, 46)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(textFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(textFieldID, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(textFieldLast, javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(textFieldRegion, javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(textFieldPwd, javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(textFieldHasta, javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(textFieldDesde, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))))
          .addGroup(layout.createSequentialGroup()
            .addComponent(jButton1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton3)))
        .addContainerGap(57, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel1)
          .addComponent(textFieldID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel2)
          .addComponent(textFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel3)
          .addComponent(textFieldRegion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel4)
          .addComponent(textFieldDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel5)
          .addComponent(textFieldHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel6)
          .addComponent(textFieldPwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel7)
          .addComponent(textFieldLast, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jButton1)
          .addComponent(jButton2)
          .addComponent(jButton3))
        .addGap(23, 23, 23))
    );
    pack();
  }// </editor-fold>//GEN-END:initComponents
  
  private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    try {
      PreparedStatement stmt = cnn.prepareStatement(SQL_DELETE_1);
      stmt.setString(1, textFieldID.getText().trim());
      long ar = stmt.executeUpdate();
      if (ar == 1) {
        JOptionPane.showMessageDialog(this, "Registro Eliminado!", "Vendedores", JOptionPane.INFORMATION_MESSAGE);
        clearFields(true);
        textFieldID.requestFocusInWindow();
      }
      stmt.close();
    } catch (SQLException ex) {
      ex.printStackTrace();
      JOptionPane.showMessageDialog(this, ex, "Vendedores", JOptionPane.INFORMATION_MESSAGE);
    }
  }//GEN-LAST:event_jButton3ActionPerformed
  
  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    if (mode.equals("add")) {
      String validate = validateFields();
      if (validate.equals("")) {
        try {
          PreparedStatement stmt = cnn.prepareStatement(SQL_INSERT_1);
          stmt.setString(1, textFieldID.getText().trim().toUpperCase());
          stmt.setString(2, textFieldName.getText().trim());
          stmt.setString(3, textFieldRegion.getText().trim());
          stmt.setLong(4, Long.parseLong(textFieldHasta.getText().trim()));
          stmt.setLong(5, Long.parseLong(textFieldDesde.getText().trim()));
          stmt.setString(6, textFieldPwd.getText().trim());
          stmt.setLong(7, Long.parseLong(textFieldLast.getText().trim()));
          long ar = stmt.executeUpdate();
          if (ar == 1) {
            JOptionPane.showMessageDialog(this, "Registro Insertado!", "Vendedores", JOptionPane.INFORMATION_MESSAGE);
            clearFields(true);
            textFieldID.requestFocusInWindow();
          }
          stmt.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
          JOptionPane.showMessageDialog(this, ex, "Vendedores", JOptionPane.INFORMATION_MESSAGE);
        }
      } else {
        JOptionPane.showMessageDialog(this, validate, "Vendedores", JOptionPane.INFORMATION_MESSAGE);
      }
    } else {
      String validate = validateFields();
      if (validate.equals("")) {
        try {
          PreparedStatement stmt = cnn.prepareStatement(SQL_UPDATE_1);
          stmt.setString(7, textFieldID.getText().trim());
          stmt.setString(1, textFieldName.getText().trim());
          stmt.setString(2, textFieldRegion.getText().trim());
          stmt.setLong(3, Long.parseLong(textFieldHasta.getText().trim()));
          stmt.setLong(4, Long.parseLong(textFieldDesde.getText().trim()));
          stmt.setString(5, textFieldPwd.getText().trim());
          stmt.setLong(6, Long.parseLong(textFieldLast.getText().trim()));
          long ar = stmt.executeUpdate();
          if (ar == 1) {
            JOptionPane.showMessageDialog(this, "Registro Actualizado!", "Vendedores", JOptionPane.INFORMATION_MESSAGE);
            clearFields(true);
            textFieldID.requestFocusInWindow();
          }
          stmt.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
          JOptionPane.showMessageDialog(this, ex, "Vendedores", JOptionPane.INFORMATION_MESSAGE);
        }
      } else {
        JOptionPane.showMessageDialog(this, validate, "Vendedores", JOptionPane.INFORMATION_MESSAGE);
      }
    }
  }//GEN-LAST:event_jButton2ActionPerformed
  
  private void textFieldIDFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textFieldIDFocusLost
    if (!textFieldID.getText().trim().equals("")) {
      try {
        PreparedStatement stmt = cnn.prepareStatement(SQL_SELECT_1);
        stmt.setString(1, textFieldID.getText().trim());
        ResultSet rs = stmt.executeQuery();
        boolean idExists = false;
        while (rs.next()) {
          idExists = true;
          textFieldName.setText(rs.getString("name"));
          textFieldRegion.setText(rs.getString("region"));
          textFieldDesde.setText(String.valueOf(rs.getLong("bottom_serial")));
          textFieldHasta.setText(String.valueOf(rs.getLong("top_serial")));
          textFieldPwd.setText(rs.getString("comments"));
          textFieldLast.setText(String.valueOf(rs.getLong("last_serial")));
        }
        
        if (idExists) {
          mode = "upd";
        } else {
          mode = "add";
          clearFields(false);
        }
        rs.close();
        stmt.close();
      } catch (SQLException ex) {
        ex.printStackTrace();
      }
    }
  }//GEN-LAST:event_textFieldIDFocusLost
  
  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    
    /* Boton Nuevo */
    
    mode="add";
    clearFields(true);
    textFieldID.requestFocusInWindow();
  }//GEN-LAST:event_jButton1ActionPerformed
  
  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new SalesmanUI().setVisible(true);
      }
    });
  }
  
  public Connection getCnn() {
    return cnn;
  }
  
  public void setCnn(Connection cnn) {
    this.cnn = cnn;
  }
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JButton jButton3;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JTextField textFieldDesde;
  private javax.swing.JTextField textFieldHasta;
  private javax.swing.JTextField textFieldID;
  private javax.swing.JTextField textFieldLast;
  private javax.swing.JTextField textFieldName;
  private javax.swing.JTextField textFieldPwd;
  private javax.swing.JTextField textFieldRegion;
  // End of variables declaration//GEN-END:variables
  
}
